﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Utils
{
    /// <summary>
    /// Txt文件存储操作类
    /// </summary>
    public class TxtHelp
    {
        /// <summary>
        /// 读取Txt文件每一行数据
        /// </summary>
        /// <param name="docUrl"></param>
        /// <returns></returns>
        public static List<string> TxtReadLine(string docUrl)
        {
            List<string> dataList = new List<string>();
            using (StreamReader stream = new StreamReader(docUrl, Encoding.UTF8))
            {
                while (!stream.EndOfStream)
                {
                    string data = stream.ReadLine();
                    dataList.Add(data);
                }
                stream.Close();
            }
            return dataList;
        }

        /// <summary>
        /// 向Txt文件新增数据
        /// </summary>
        /// <param name="docUrl"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static bool TxtWrite(string docUrl, string data)
        {
            try
            {
                File.AppendAllText(docUrl,string.Format("{0}\r\n",data));
                //FileStream fs = new FileStream(docUrl, FileMode.Create, FileAccess.ReadWrite);
                //fs.Seek(0, SeekOrigin.Begin);
                //fs.SetLength(0);
                //StreamWriter sw = new StreamWriter(fs);
                //sw.WriteLine(data);
                //sw.Close();
                //fs.Close();
                return true;
            }
            catch
            {

                return false;
            }
        }


        /// <summary>
        /// 清空Txt文件内容
        /// </summary>
        /// <param name="docUrl"></param>
        public static void TxtClear(string docUrl)
        {
            using (FileStream stream = File.Open(docUrl, FileMode.OpenOrCreate, FileAccess.Write))
            {
                stream.Seek(0, SeekOrigin.Begin);
                stream.SetLength(0);
                stream.Close();
            }
        }





    }
}
